$(document).ready(function() {
    var g = function (id){ //寻找DOM方法
        if( id.substr(0,1) == '.'){
            return document.getElementsByClassName(id.substr(1));
      Name  }
        return document.getElementById(id);
    };
    var menuBar =[//按钮的配置数组
        {bar:1,cl:'glyphicon glyphicon-arrow-left',label:'撤销',id:'ctrl_z'},
        {bar:2,cl:'glyphicon glyphicon-arrow-right',label:'重做',id:'ctrl_y'},
        {bar:3,cl:'glyphicon glyphicon-bold',label:'加粗',id:'bold'},
        {bar:4,cl:'glyphicon glyphicon-italic',label:'斜体',id:'italic'},
        {bar:5,cl:'glyphicon glyphicon-header',label:'一级标题',id:'h1'},
        {bar:6,cl:'glyphicon glyphicon-header',label:'二级标题',id:'h2'},
        {bar:7,cl:'glyphicon glyphicon-header',label:'三级标题',id:'h3'},
        {bar:8,cl:'glyphicon glyphicon-header',label:'四级标题',id:'h4'},
        {bar:9,cl:'glyphicon glyphicon-header',label:'五级标题',id:'h5'},
        {bar:10,cl:'glyphicon glyphicon-header',label:'六级标题',id:'h6'},
        {bar:11,cl:'glyphicon glyphicon-eye-open',label:'预览',id:'eye'},
        {bar:12,cl:'glyphicon glyphicon-question-sign',label:'帮助',id:'que'},
        {bar:13,cl:'glyphicon glyphicon-info-sign',label:'关于',id:'about'}
    ];
    function addButton(){//添加按钮方法
        var bar=g('btn-group').innerHTML.replace(/^\s*/,'').replace(/^\s*/,'');
        var out_bar= [];
        for(i in menuBar){
            var _html_bar = bar.replace(/{{glyphicon}}/g,menuBar[i].cl)
                                .replace(/{{id}}/g,menuBar[i].id)
                                .replace(/{{label}}/g,menuBar[i].label);
            out_bar.push(_html_bar);
        }
        g('btn-group').innerHTML = out_bar.join('');
    };
    function addPublic(id){
        if(id==0){
            $("#is option[value='0']").attr("selected","true");
        }else{
            $("#is option[value='1']").attr("selected","true");
        }
    }
    var cm = CodeMirror.fromTextArea(document.getElementById("code"),{ //实例化codemirror对象
        mode: "markdown",
        lineNumbers: true,
        lineWrapping: true,
        extraKeys: {"Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }},
        foldGutter: true,
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
        matchBrackets:true
    }); 
    /*初始化按钮和按钮提示*/     
    addButton(); 
    $('[data-toggle="tooltip"]').tooltip();
    $('#about').attr({'data-toggle':'modal','data-target':'#myModal'});
    /*按钮功能实现*/
    $("#ctrl_z").click(function(){//撤销按钮
        cm.undo();
    });
    $("#ctrl_y").click(function(){//重做按钮
        cm.redo();
    });
    $('#bold').click(function(){//加粗按钮
        var select_ct = cm.getSelection();
        select_ct='**'+select_ct+'**';
        cm.replaceSelection(select_ct);
    });
    $('#italic').click(function(){//斜体按钮
        var select_ct = cm.getSelection();
        select_ct='*'+select_ct+'*';
        cm.replaceSelection(select_ct);
    });
    /*修改标题基本方法*/
    var hum =function(num){
        var sum='';
        for(i=0;i<num;i++){
            sum+='#';
        }
        sum+=' ';
        var cursor = cm.getCursor();
        var selection = cm.getSelection();
        if (cursor.ch !== 0)
        {
            cm.setCursor(cursor.line, 0);
            cm.replaceSelection(sum + selection);
            cm.setCursor(cursor.line, cursor.ch + num+1);
        }
        else
        {
            cm.replaceSelection(sum + selection);
        }
    }
    $('#h1').click(function(){ hum(1); });//H1一级标题
    $('#h2').click(function(){ hum(2); });//H2二级标题
    $('#h3').click(function(){ hum(3); });//H3三级标题
    $('#h4').click(function(){ hum(4); });//H4四级标题
    $('#h5').click(function(){ hum(5); });//H5五级标题
    $('#h6').click(function(){ hum(6); });//H6六级标题
    $('#que').click(function(){
       window.open('markdown.html'); 
    });
    /*showdownjs翻译*/
    $('#eye').click(function(){//预览按钮
          var converter = new showdown.Converter({
            ghCodeBlocks: true,
            headerLevelStart: false,
            literalMidWordUnderscores: false,
            noHeaderId: false,
            omitExtraWLInCodeBlocks: true,
            parseImgDimensions: false,
            prefixHeaderId: false,
            simplifiedAutoLink: true,
            smoothLivePreview: false,
            strikethrough: false,
            tables: true,
            tablesHeaderId: false,
            tasklists: false
        });
        text = cm.getValue();
        html = converter.makeHtml(text); 
        $('#browser').html(html);
        hljs.initHighlightingOnLoad();//语法高亮
    });
    
    addPublic($('#isPublic').val());
    /*更新操作*/
    $('#save').click(function(){
        var content = cm.getValue();
        var username = $.cookie('username');
        var filename = $('#filename').val();
        var url = './p/'+username+'/'+filename;
        var isPublic=$('#is').val();
        if(content==''){
            alert('您尚未输入任何内容！');
        }else{
            $.post('mk_save.php',{filename:filename,content:content,isPublic:isPublic},function(msg){  
                function disp_confirm(){
                    var r=confirm("保存成功，是否跳转预览？")
                    if (r==true){
                        document.location.href=url;
                    }
                }
                var data = eval('('+msg+')');
                if(data['code']==1){
                    disp_confirm();
                }else{
                    alert('保存失败！请联系系统管理员zhonger#(@)wl27.cn');
                }
            });
        }
    });
});


    
